package com.savitar.menu.service;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.savitar.common.annotation.Create;
import com.savitar.common.annotation.Update;
import com.savitar.menu.dao.MenuMapper;
import com.savitar.menu.entity.Menu;
import com.savitar.menu.entity.MenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * (Menu)服务接口
 *
 * @author Savitar
 * @since 2021-05-16 09:28:26
 */
@Service
public class MenuService extends ServiceImpl<MenuMapper, Menu> {

    @Autowired
    private MenuMapper mapper;

    public List<MenuVo> tree() {
        List<MenuVo> list = mapper.listByLevel(1);
        return generateTree(list);
    }

    List<MenuVo> generateTree(List<MenuVo> list) {
        list.forEach(menu -> {
            menu.setChildren(generateTree(listByPid(menu.getPkId())));
        });
        return list;
    }

    List<MenuVo> listByPid(String pid) {
        return mapper.listByPid(pid);
    }

    public List<MenuVo> treeByRole(String roleId) {
        List<MenuVo> menuVos = mapper.listByLevelAndRole(1, roleId);
        return generateTreeByRole(menuVos, roleId);
    }

    private List<MenuVo> generateTreeByRole(List<MenuVo> menuVos, String roleId) {
        menuVos.forEach(menu -> {
            menu.setChildren(generateTreeByRole(listByPidAndRole(menu.getPkId(), roleId), roleId));
        });
        return menuVos;
    }

    List<MenuVo> listByPidAndRole(String pid, String roleId) {
        return mapper.listByPidAndRole(pid, roleId);
    }

    @Create
    public Menu create(Menu createVo) {
        createVo.setPkId(IdUtil.simpleUUID());
        createVo.insert();
        return createVo;
    }

    @Update
    public Menu update(Menu updateVo) {
        updateVo.updateById();
        return updateVo;
    }

    public Menu deleteById(String id) {
        Menu one = lambdaQuery().eq(Menu::getPkId, id).one();
        one.deleteById();
        return one;
    }

    public List<String> listMenuIdByRole(String role) {
        return mapper.listMenuIdByRole(role);
    }

    @Transactional
    public int createRole2Menu(String roleId, List<String> menus) {
        mapper.deleteByRole(roleId);
        return mapper.createRole2Menu(roleId, menus);
    }
}